package middleware

import (
	"github.com/gin-gonic/gin"
	"shejiao/base"
	"shejiao/pkg/common"
	"shejiao/pkg/util"
	"strconv"
)

func UserMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		// token
		token := c.GetHeader("token")
		var userInfo util.UserAuthToken
		err := util.DecodeToken(base.Config.App.AuthKey, token, &userInfo)

		if err != nil && !base.Config.Debug {
			common.Response.NoAuth(c, gin.H{"err": err.Error()})
			c.Abort()
			return
		}

		if userInfo.RoleType != "user" && !base.Config.Debug {
			common.Response.NoAuth(c, gin.H{"err": err.Error()})
			c.Abort()
			return
		}

		if base.Config.Debug == true && userInfo.RoleId == 0 {
			roleId, _ := strconv.Atoi(token)
			userInfo = util.UserAuthToken{RoleId: int64(roleId), RoleType: "user"}
		}

		c.Set("token", token)
		c.Set("role_id", userInfo.RoleId)
		c.Set("role_type", userInfo.RoleType)
		c.Next()
	}
}
